// components/chat-message.tsx
"use client";
import { forwardRef, Suspense, useEffect, useMemo, useState } from "react";
import { format } from "date-fns";
import { Bot, User, Clipboard, ThumbsUp, ThumbsDown, ClipboardCheck } from "lucide-react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar";
import Markdown from "./Markdown";

export interface MessageProps {
  id: string;
  content: string;
  role: 'system' | 'user' | 'assistant' | 'data';
  timeVisible?: boolean;
  timestamp?: Date | undefined;
  userAvatar?: string;
  assistantAvatar?: string;
  copyVisible?: boolean;
  actionsVisible?: boolean;
  onLike?: () => void;
  onDislike?: () => void;
}
const ChatMessage = forwardRef<HTMLDivElement, MessageProps>(
  ({ 
    content, 
    role, 
    timestamp, 
    userAvatar,
    assistantAvatar,
    copyVisible=false,
    actionsVisible = false,
    onLike,
    onDislike
  }, ref) => {
    const isUser = role === "user";
    const [isHovering, setIsHovering] = useState(false);
    const [copied, setCopied] = useState(false);
    const [liked, setLiked] = useState(false);
    const [disliked, setDisliked] = useState(false);
    const formattedTime = useMemo(() => {
        if (!timestamp) return "";  // 处理空时间戳
        try {
          return format(timestamp, "yyyy-MM-dd HH:mm:ss");
        } catch {
          return "";
        }
      }, [timestamp]);

    const handleCopy = async () => {
      try {
        
        await navigator.clipboard.writeText(content);
        toast.info("内容已复制到剪贴板",);
        setCopied(true);
      } catch (err) {
        toast.error("复制失败");
      }
    };

    useEffect(() => {
        if (copied) {
          const timer = setTimeout(() => setCopied(false), 2000);
          return () => clearTimeout(timer);
        }
      }, [copied]);

    const handleLike = () => {
        setLiked(!liked);
        if (disliked) setDisliked(false);
        onLike?.();
      };
  
      const handleDislike = () => {
        setDisliked(!disliked);
        if (liked) setLiked(false);
        onDislike?.();
      };

    return (
      <div
        ref={ref}
        className={cn(
          "group flex items-start gap-3 py-4 relative",
          isUser && "justify-end"
        )}
        onMouseEnter={() => setIsHovering(true)}
        onMouseLeave={() => setIsHovering(false)}
      >
        {/* 左侧机器人头像 */}
        {!isUser && (
          <Avatar className="h-10 w-10">
            <AvatarImage src={assistantAvatar} />
            <AvatarFallback className="bg-primary/10">
              <Bot className="h-6 w-6 text-primary" />
            </AvatarFallback>
          </Avatar>
        )}
        {/* 时间戳容器（左侧） */}
        {!isUser && formattedTime && (
          <time
            className={cn(
              "absolute text-xs opacity-70 -bottom-2 left-14",
              "transition-opacity hover:opacity-100",
              "text-muted-foreground"
            )}
          >
            {formattedTime}
          </time>
        )}
        <Card
          className={cn(
            "max-w-[85%] space-y-2 px-4 py-2 relative",
            "transition-all duration-200 ease-in-out",
            isUser 
              ? "bg-primary text-primary-foreground hover:bg-primary/90" 
              : "bg-muted hover:bg-muted/90"
          )}
        >
          {/* 消息内容 */}
          <div className="text-sm leading-relaxed pr-4 mx-w-[100%]">
              <Markdown content={content}></Markdown>
          </div>


          {/* 底部操作栏 */}
          {(formattedTime || actionsVisible || copyVisible) &&(
            <div className="flex justify-between items-center">
            
                {(actionsVisible || copyVisible) && (
                    <div className={cn(
                        "absolute flex items-center gap-1",
                        "bottom-1 right-1",
                        "transition-opacity duration-200",
                        isHovering ? "opacity-100" : "opacity-0"
                    )}>
                    {copyVisible && (
                    <Button
                    variant="ghost"
                    size="sm"
                    className={cn(
                        "h-6 w-6 p-1 transition-all",
                        "hover:scale-110 hover:bg-foreground/5",
                        isUser 
                        ? "text-primary-foreground/80 hover:text-primary-foreground" 
                        : "text-muted-foreground/80 hover:text-muted-foreground"
                    )}
                    onClick={handleCopy}
                    >
                     {copied ? (
                        <ClipboardCheck className="h-3 w-3 text-green-500" />
                        ) : (
                        <Clipboard className="h-3 w-3" />
                        )}
                    </Button>
                    )}
                    {actionsVisible && !isUser && (
                    <>
                        <Button
                            variant="ghost"
                            size="sm"
                            className={cn(
                                "h-6 w-6 p-1 transition-all",
                                "hover:scale-110 hover:text-green-500",
                                liked 
                                ? "text-green-500 hover:bg-green-500/10" 
                                : "text-muted-foreground/80 hover:bg-green-500/10"
                            )}
                            onClick={handleLike}
                            >
                            <ThumbsUp className={cn(
                                "h-3 w-3",
                                liked && "fill-current stroke-[0.5]"
                                )} />
                        </Button>
                        <Button
                            variant="ghost"
                            size="sm"
                            className={cn(
                                "h-6 w-6 p-1 transition-all",
                                "hover:scale-110 hover:text-red-500",
                                disliked 
                                ? "text-red-500 hover:bg-red-500/10" 
                                : "text-muted-foreground/80 hover:bg-red-500/10"
                            )}
                            onClick={handleDislike}
                            >
                            <ThumbsDown className={cn(
                                "h-3 w-3",
                                disliked && "fill-current stroke-[0.5]"
                                )} />
                        </Button>
                    </>
                    )}
                    
                </div>
                )}
            </div>
            )}
        </Card>
        
        {/* 右侧用户头像 */}
        {isUser && (
          <Avatar className="h-10 w-10">
            <AvatarImage src={userAvatar} />
            <AvatarFallback className="bg-primary">
              <User className="h-6 w-6 text-primary-foreground" />
            </AvatarFallback>
          </Avatar>
        )}
        {/* 右侧时间戳 */}
        {isUser && formattedTime && (
        <time className={cn(
            "w-full absolute -bottom-2 right-12",
            "text-xs opacity-70 transition-opacity"
            )}>
            {formattedTime}
        </time>
        )}
      </div>
    );
  }
);

ChatMessage.displayName = "ChatMessage";
export { ChatMessage };
